import React, { useRef } from 'react'
import { Row, Col, Button, Input, Form } from 'antd'
import Text from '@components/Text'
const { Item } = Form

function onSMSPressKey (e, formRef) {
  if (e.which !== 13) {
    return false
  }
  e.stopPropagation()
  e.preventDefault()
  formRef.current.submit()
}

function TextLine ({ emscode, readEmsPdf, pdfLoading }) {
  return (
    <Form initialValues={{ emscode }}>
      <Row>
        <Col span={12}>
          <Item name='emscode' label='邮单号' labelCol={{ span: 6 }}>
            <Text />
          </Item>
        </Col>
        <Col span={12} style={{ textAlign: 'right' }}>
          {emscode ? <Button type='link' disabled={pdfLoading} onClick={() => readEmsPdf(emscode)}>打印邮单轨迹</Button> : null}
        </Col>
      </Row>
    </Form>
  )
}

function InputLine ({ emscode, setEmscode, readEmsPdf, pdfLoading }) {
  const formRef = useRef(null)
  return (
    <Form ref={formRef} initialValues={{ emscode }} onFinish={d => setEmscode(d.emscode ? d.emscode.trim() : '')}>
      <Row>
        <Col span={12}>
          <Item name='emscode' label='邮单号' labelCol={{ span: 6 }} rules={[{ required: true, message: '邮单号不能为空' }]}>
            <Input placeholder='请输入邮单号' autoFocus onKeyPress={e => onSMSPressKey(e, formRef)} />
          </Item>
        </Col>
        <Col span={4}>
          <Button type='link' htmlType='submit'>{emscode ? '修改' : '确定'}</Button>
        </Col>
        <Col span={8} style={{ textAlign: 'right' }}>
          {emscode ? <Button type='link' disabled={pdfLoading} onClick={() => readEmsPdf(emscode)}>打印邮单轨迹</Button> : null}
        </Col>
      </Row>
    </Form>
  )
}

function Main ({ emscode, setEmscode, readEmsPdf, modifiable, pdfLoading }) {
  return (
    <div>
      {modifiable ? (
        <InputLine emscode={emscode} setEmscode={setEmscode} readEmsPdf={readEmsPdf} pdfLoading={pdfLoading} />
      ) : (
        <TextLine emscode={emscode} readEmsPdf={readEmsPdf} pdfLoading={pdfLoading} />
      )}
    </div>
  )
}

export default Main
